﻿using MediatR;
using THE_WIND_RISES.Common.Dtos;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Production_Set.API.Application.Commands.Technology;
using Production_Set.API.Controllers.SU;
using Production_Set.API.Application.Commands.WorkCenters;
using Return.Enum;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using THE_WIND_RISES.Common.Domans.Produce.WorkCenter_;
using System.Globalization;
using THE_WIND_RISES.Common.Domans.Produce.Customers;
using SlaughterItem.Common.Infrastructures.Interfaces;

namespace Production_Set.API.Controllers.WorkCenterControllers_W
{

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WorkCenterController : ControllerBase
    {
        private readonly IBaseRepository<WorkCenter> WorkCenterRepository;
        /// <summary>
        /// 中介者
        /// </summary>
        private readonly IMediator mediator;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator"></param>
        /// <param name="logger"></param>
        public WorkCenterController(IMediator mediator, IBaseRepository<WorkCenter> workCenterRepository)
        {
            this.mediator = mediator;
            WorkCenterRepository = workCenterRepository;
        }
        /// <summary>
        /// 添加工作中心
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> WorkCenterAddData(WorkCenterAddCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 工作中心删除
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> WorkCenterDeleteData(WorkCenterDeleteCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 工作中心审批
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> WorkCenterUpdApproveData(WorkCenterUpdApproveCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 反填工作中心信息及其资源行信息
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> WorkCenterReverseData(WorkCenterReverseCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 逻辑删除工作中心的资源行信息
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> workCentersWealthDeleteData(workCentersWealthDeleteCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 工作中心信息修改
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> WorkCenterUpdData(WorkCenterUpdCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 工作中心导入
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public dynamic GetImport(IFormFile file)
        {
            var result = new Result() { Code = (int)CommonErrorCodes.Search };
            //获取文件扩展名 判断上传的文件类型是否正确
            var ext = Path.GetExtension(file.FileName);
            if (ext == ".xls" || ext == ".xlsx")
            {

            }
            else
            {
                return "您上传的文件类型不正确";
            }

            using (MemoryStream ms = new MemoryStream())
            {
                file.CopyTo(ms);
                ms.Position = 0;
                //根据文件扩展名创建对应的工作簿对象(HSSFWorkbook用于.xls，XSSFWorkbook用于.xlsx)
                //获取工作簿
                IWorkbook wb = null;
                if (ext == ".xls")//创建97-2003
                {
                    wb = new HSSFWorkbook(ms);
                }
                else//创建2007及以上版本
                {
                    wb = new XSSFWorkbook(ms);
                }

                //获取sheet 获取工作簿中的第一个工作表
                ISheet sheet = wb.GetSheetAt(0);

                int totalRows = sheet.LastRowNum;//总行数
                int totalCells = sheet.GetRow(0).LastCellNum;//总列数

                // 创建一个用于存储解析后的数据的列表
                var farrowingsList = new List<WorkCenter>();

                //循环总行数 开头必须是1 不然从表头开始
                //遍历工作表的每一行（从第二行开始，因为第一行通常是表头）
                for (int i = 1; i <= totalCells; i++)
                {
                    //获取当前行
                    IRow row = sheet.GetRow(i);

                    //这个类必须写到循环里边 不然你批量添加只能添加一行 
                    var dto = new WorkCenter();// 在循环内创建新的对象实例
                    if (row == null) continue;//跳过空行
                    
                    ////下标从0开始 导入时 外键需进行判断 客户不知道你是外键 只会输入文字 需要在后台判断
                    //var earnumber = row.GetCell(0).ToString();
                    //var basic = SalesDetails.GetAll().Where(z => z.SalesDetailsOrderNum == earnumber).FirstOrDefault();
                    //dto.CustomerId = basic.CustomerId;

                    //日期转换
                    //日期在excel表中必须是年月日格式 但不能加时分秒 (注意!!!!)
                    string[] multipleFormats = { "dd-M月-yyyy", "yyyy-M-dd" };//, "yyyy-MM-dd" , "yyyy/MM/dd", "yyyy/M/dd"
                    string inputDate = row.GetCell(5).ToString();
                    DateTime parsedDate;
                    foreach (var format in multipleFormats)
                    {
                        if (DateTime.TryParseExact(inputDate, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
                        {
                            dto.CreateTime = Convert.ToDateTime(parsedDate.ToString("yyyy-MM-dd"));
                            break;//成功解析后跳出循环
                        }
                    }
                    dto.WorkCenterId = Convert.ToInt32(row.GetCell(0).ToString());
                    dto.WorkCenterNum = row.GetCell(1).ToString();
                    dto.WorkCenterName = row.GetCell(2).ToString();
                    dto.WorkCenterType = row.GetCell(3).ToString();
                    dto.ClassesData = row.GetCell(4).ToString();
                    dto.CreateName = row.GetCell(6).ToString();
                    dto.WorkCenterState = row.GetCell(7).ToString() == "有效" ? true : false;
                    dto.ApprovalState = row.GetCell(8).ToString() == "通过" ? 1 : row.GetCell(8).ToString() == "驳回" ? 2 : 0;
                    //添加到数据集合中
                    farrowingsList.Add(dto);
                }
                //跳出循环后 使用AddRange进行批量添加
                string sql = "insert into workCenters values(@WorkCenterId,@WorkCenterNum,@WorkCenterName,@WorkCenterType,@ClassesData,@CreateTime,@CreateName,@WorkCenterState,@ApprovalState,@IsDelWorkCenter);";
                var res = WorkCenterRepository.AddRound(sql, farrowingsList);
                //判断
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCodes.Success;
                    result.Msg = "导入成功";

                }
                else
                {
                    result.Msg = "导入失败";
                }

                return result;
            }
            
        }
    }
}
